const app = getApp();
var util = require('../../utils/util.js')
var WxParse = require('../../wxParse/wxParse.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    autoplay: true,
    interval: 3000,
    duration: 1000,
    goodsDetail: {},
    swiperCurrent: 0,
    hasMoreSelect: false,
    selectSize: "",
    selectSizePrice: 0,
    shopNum: 0,
    hideShopPopup: true,
    buyNumber: 0,
    buyNumMin: 0,
    buyNumMax: 0,
    propertyChildIds: "",
    propertyChildNames: "",
    canSubmit: false, //  选中规格尺寸时候是否允许加入购物车
    favorite: false,
    CurrentPid: 0,
    ReviewListLength: 0,
    animationData: "",
    showModalStatus: false,
    skuTitles: [],
    attrvalue: "",
    img: "",
    TotalCount: "",
    groupBuyInfor: {},
    timer: {
      days: 0,
      hours: 0,
      minutes: 0,
      seconds: 0,
      leftTime: 0
    },
    shouwTimer: true,
    showTimer: true,
    disId: 0,
    agentId: 0,
    animationData2: "",
    showModalStatus2: false,
    productCode: "",
    pathGoods: "",
    mallName: "",
    startDate: 0,
    FromAccountNick: "",
    FromAccountImage: "",
    showTopPopup: false,
    FromAccount: "",
    productImageList: [],
    isAiweapp: true,
    query: ''
  },

  preview: function () {
    var that = this
    wx.previewImage({
      current: that.data.productCode, // 当前显示图片的http链接
      urls: [that.data.productCode] // 需要预览的图片http链接列表
    })
  },
  //获取商品二维码
  getWxaCode: function (path) {
    console.log(path);
    var that = this
    wx.request({
      url: app.globalData.host + "/api/Store/GetWxaCodeFile",
      data: {
        storeId: app.globalData.storeId,
        // path: '/pages/pintuan-details/index?id=' + this.data.CurrentPid,
        path: path,
        storeappid: app.globalData.storeAppId
      },
      success: function (res) {
        console.log(res);
        if (res.data.Code == 0) {
          if (res.data.Data) {
            that.setData({
              productCode: 'https://static.711688.net.cn/upload/user/' + res.data.Data
            })
          }
        }
      },
    })
  },

  //事件处理函数
  swiperchange: function (e) {
    this.setData({
      swiperCurrent: e.detail.current
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    var that = this;
    util.isAiWeApp(app, function (data) {
      that.setData({ isAiweapp: data })
    });
    that.getGroupBuyProductInfo();
    let currentPid = 0;
    let params = decodeURIComponent(e.scene);
    console.log('小程序码携带的参数', params);
    if (params && params != 'undefined') {//扫描小程序二维码进入
      let param = params.match(/p=(\S*)/)[1];//参数
      let plist = param.toString().split('#');
      console.log(plist);
      if (plist[0]) {
        wx.setStorageSync("disid", plist[0]);
      }
      if (plist[1]) {
        wx.setStorageSync("agentid", plist[1]);
      }
      currentPid = plist[2];
    }else{
      if (e.agentId) {
        wx.setStorageSync("agentid", e.agentId);
      }
      if (e.disId) {
        wx.setStorageSync("disid", e.disId);
      }
      currentPid = e.id;
    }
    that.setData({ CurrentPid: currentPid });
    if (e.isFriendState) {
      that.getGoodsInfo();
      if (that.data.shouwTimer) {
        that.intervalTimer();
      }
    }
  },
  intervalTimer: function () {
    var that = this;
    var timers = setInterval(function () {
      var groupBuyInfor = that.data.groupBuyInfor
      var EndTime = groupBuyInfor.EndTime
      var StartTime = groupBuyInfor.StartTime
      var timearr = EndTime.replace(" ", ":").replace(/\:/g, "-").split("-");//分割日期正则
      var year = timearr[0]
      var month = timearr[1]
      var day = timearr[2]
      var hour = timearr[3]
      var minute = timearr[4]
      var second = timearr[5]
      if (StartTime == EndTime || !that.data.shouwTimer || !that.data.showTimer) {
        clearInterval(timers)//清除计时
      } else {
        that.leftTimer(year, month, day, hour, minute, second)
      }
    }, 1000)
  },
  //时间计时
  leftTimer: function (year, month, day, hour, minute, second) {
    var that = this;
    var leftTime = (new Date(year, month - 1, day, hour, minute, second)) - (new Date()); //计算剩余的毫秒数 
    var days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10); //计算剩余的天数 
    var hours = parseInt(leftTime / 1000 / 60 / 60 % 24, 10); //计算剩余的小时 
    var minutes = parseInt(leftTime / 1000 / 60 % 60, 10);//计算剩余的分钟 
    var seconds = parseInt(leftTime / 1000 % 60, 10);//计算剩余的秒数 
    days = that.checkTime(days);
    hours = that.checkTime(hours);
    minutes = that.checkTime(minutes);
    seconds = that.checkTime(seconds);
    var timer = {}
    timer.days = days
    timer.hours = hours
    timer.minutes = minutes
    timer.seconds = seconds
    timer.leftTime = leftTime
    if (leftTime > 0) {
      that.setData({
        timer: timer
      })
    } else {
      that.setData({
        showTimer: false
      })
    }
  },
  checkTime: function (i) { //将0-9的数字前面加上0，例1变为01 
    if (i < 10) {
      i = "0" + i;
    }
    return i;
  },

  selectGoods: function (e) {
    console.log("点击商品评价")
    console.log(e)
    wx.navigateTo({
      url: '/pages/pingjia-list/index?pid=' + this.data.CurrentPid
    })
  },
  numJianTap: function () {
    if (this.data.buyNumber > this.data.buyNumMin) {
      var currentNum = this.data.buyNumber;
      currentNum--;
      this.setData({
        buyNumber: currentNum
      })
    }
  },
  numJiaTap: function (e) {
    console.log(e)
    if (e.detail.value) {
      if (this.data.buyNumber < this.data.buyNumMax) {
        this.setData({
          buyNumber: e.detail.value
        })
      }
    } else {
      if (this.data.buyNumber < this.data.buyNumMax) {
        var currentNum = this.data.buyNumber;
        currentNum++;
        this.setData({
          buyNumber: currentNum
        })
      }
    }
  },
  addShopCar: function (e) {
    console.log(e)
    if (e != 0) {
      var add = e.currentTarget.dataset.add
    }
    var that = this;
    if (this.data.buyNumber < 1) {
      wx.showModal({
        title: '提示',
        content: '暂时缺货哦~',
        showCancel: false
      })
      return;
    }

    wx.request({
      url: app.globalData.host + '/api/cart/AddProduct',
      data: {
        uid: app.globalData.userInfo.Uid,
        pid: that.data.CurrentPid,
        buyCount: that.data.buyNumber
      },
      success: function (res) {
        console.log(res);
        if (res.data.Code == 0) {
          that.setData({
            shopNum: res.data.Data
          });
          wx.showToast({
            title: '加入购物车成功',
            icon: 'success',
            duration: 2000,
            success: function () {
              if (add != 1) {
                that.goShopCar();
              }
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  goShopCar: function () {
    wx.reLaunch({
      url: "/pages/shop-cart/index"
    });
  },
  tobuy: function (e) {
    var isSkuProduct = e.currentTarget.dataset.sku
    if (isSkuProduct > 0) {
      this.showModal()
    } else {
      if (this.data.buyNumber < 1) {
        wx.showModal({
          title: '提示',
          content: '暂时缺货哦~',
          showCancel: false
        })
        return;
      }
      this.addShopCar(0);
    }
  },
  favorite: function (e) {
    console.log(e);
    var that = this;
    var pid = e.currentTarget.dataset.id;
    wx.request({
      url: app.globalData.host + '/api/user/ProductFavorite',
      data: {
        pid: pid,
        uid: app.globalData.userInfo.Uid
      },
      success: function (res) {
        console.log(res);
        if (res.data.Code == 0) {
          var oldF = that.data.favorite;
          if (oldF) {
            wx.showModal({
              title: '取消收藏成功',
              content: '',
              showCancel: false
            })
          } else {
            wx.showModal({
              title: '收藏成功',
              content: '',
              showCancel: false
            })
          }
          that.setData({ favorite: !oldF })
        }

      }
    })
  },
  initPage: function () {
    var that = this;
    var getLocationPromisified = util.wxPromisify(that.getShopCart)
    getLocationPromisified({

    }).then(that.checkFavorite())
      .then(that.getGoodsInfo())
      .then(that.pingjiaList())
      .catch(function (res) {
        console.error("failed" + res)
      })
  },

  //判断收藏
  checkFavorite: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/user/CheckProductFavorite',
      data: {
        pid: that.data.CurrentPid,
        uid: app.globalData.userInfo.Uid
      },
      success: function (res) {
        var f = res.data.Data;
        that.setData({ favorite: f })
      }
    })
  },

  //获取购物车数据
  getShopCart: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/cart/index',
      data: {
        uid: app.globalData.userInfo.Uid
      },
      success: function (res) {
        console.log(res);
        if (res.data.Code == 0) {
          that.setData({ shopNum: res.data.Data.TotalCount })
        }

      }
    })
  },

  //获取商品信息getGoodsInfo
  getGoodsInfo: function () {
    wx.showLoading({
      title: '加载中',
    })
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/store/Product',
      data: {
        pid: that.data.CurrentPid
      },
      success: function (res) {
        wx.hideLoading();
        var p = res.data.Data;
        if (!p.ProductInfo || p.ProductInfo.State != 0) {
          wx.showModal({
            title: '商品已下架',
            content: '',
            showCancel: false
          })
          return;
        }
        p.ProductInfo.countPrice = parseInt(p.ProductInfo.MarketPrice - p.ProductInfo.ShopPrice)//市场价和本店价价格差
        if (p.ProductInfo.ShowImg) {
          p.ProductInfo.ShowImg = app.globalData.image800_800host + p.ProductInfo.ShowImg;
        }
        for (var i = 0; i < p.ProductImageList.length; i++) {
          p.ProductImageList[i].ShowImg = app.globalData.image800_800host + p.ProductImageList[i].ShowImg;
        }
        that.getImgInfoHeight(p.ProductImageList)
        if (p.ExtGiftList) {
          for (var i = 0; i < p.ExtGiftList.length; i++) {
            p.ExtGiftList[i].ShowImg = app.globalData.image190_190host + p.ExtGiftList[i].ShowImg;
          }
        }

        var selectSizeTemp = "";
        var pnames = "";
        if (p.CurrProductSkuList.length > 0) {
          for (var i = 0; i < p.CurrProductSkuList.length; i++) {
            pnames += p.CurrProductSkuList[i].AttrName + ":";
            var value = p.CurrProductSkuList[i].AttrValue;
            if (p.CurrProductSkuList[i].IsInput) {
              value = p.CurrProductSkuList[i].InputValue;
            }
            selectSizeTemp = selectSizeTemp + " " + value;
            pnames += value + " "
          }
          that.setData({
            hasMoreSelect: true,
            selectSize: that.data.selectSize + selectSizeTemp,
            selectSizePrice: p.ProductInfo.ShopPrice,
            propertyChildNames: pnames
          });
        }
        if (p.ProductInfo.VideoSrc != "") {
          that.setData({
            showVideo: false
          })
        }

        that.setData({
          goodsDetail: p,
          selectSizePrice: p.ProductInfo.ShopPrice,
          buyNumMax: p.StockNumber,
          buyNumber: (p.StockNumber > 0) ? 1 : 0
        });
        console.log("商品详情")
        WxParse.wxParse('article', 'html', p.ProductInfo.Description, that, 5);
        util.aiCardActionRecord(22, JSON.stringify(p.ProductInfo.Name));
      }
    })
  },

  //设置图片自适应
  getImgInfoHeight: function (list) {
    var that = this;
    var heightArr = [];
    var f = 0;
    for (let h = 0; h < list.length; h++) {
      wx.getImageInfo({
        src: list[h].ShowImg,
        success: function (res) {
          list[h].width = res.width;
          list[h].height = res.height;
        },

        complete: function (res) {
          f++
          if (f == list.length) {
            console.log('执行完毕');
            for (let g = 0; g < list.length; g++) {
              //获取图片真实宽度  
              var imgwidth = list[g].width,
                imgheight = list[g].height,
                //宽高比  
                ratio = imgwidth / imgheight;
              //计算的高度值  
              var viewHeight = 750 / ratio;
              var vieheight = viewHeight
              heightArr.push(vieheight)
              list[g].imgheight = vieheight;
            }
            for (let t = 0; t < list.length; t++) {
              var maxN = that.checkMax(heightArr)
              list[t].maxHeight = maxN;
            }
            that.setData({ productImageList: list })
          } else {
            console.log("继续");
          }
        }
      })
    }
  },
  //判断最大值
  checkMax: function (heightArr) {
    var maxN = Math.max.apply(null, heightArr);
    return maxN;
  },

  //获取拼团信息
  getGroupBuyProductInfo: function () {
    var that = this
    wx: wx.request({
      url: app.globalData.host + '/api/Store/GetGroupBuyProductInfo?storeId=' + app.globalData.storeId + '&pid=' + that.data.CurrentPid,
      success: function (res) {
        if (res.data.Code == 0) {
          var GroupBuyInfor = {}
          GroupBuyInfor.GroupBuyPrice = res.data.Data.GroupBuyPrice//团购价
          GroupBuyInfor.StartTime = res.data.Data.GroupBuy.StartTime//开始时间
          GroupBuyInfor.EndTime = res.data.Data.GroupBuy.EndTime//结束时间
          GroupBuyInfor.Status = res.data.Data.GroupBuy.Status// 0:开启，1：关闭
          GroupBuyInfor.LimitBuyerCount = res.data.Data.GroupBuy.LimitBuyerCount//拼团人数
          GroupBuyInfor.BuyStatus = res.data.Data.BuyStatus//还差人数
          that.setData({
            groupBuyInfor: GroupBuyInfor
          })
        }
      }
    })
  },
  //获取评价列表
  pingjiaList: function () {
    var that = this;
    var postDatalist = {
      uid: app.globalData.userInfo.Uid,
      page: 1
    };
    wx.request({
      url: app.globalData.host + '/api/store/productreviewlist?pid=' + that.data.CurrentPid + '&page=1',
      success: (res) => {
        if (res.data.Code == 0) {
          var ReviewListTwo = [];
          that.setData({
            ReviewListLength: res.data.Data.ProductReviewList.length,
            TotalCount: res.data.Data.PageModel.TotalCount
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    util.recordActionTime(this.data.startDate, 22, this.data.CurrentPid)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    that.setData({ startDate: util.formatTime(new Date()) });
    if (app.globalData.userInfo) {
      console.log("用户信息存在");
      // that.login(function () {
      //   that.initIM()
      // });
      that.initPage();
      that.GetSharePagePath();
      if (that.data.shouwTimer) {
        that.intervalTimer();
      }
    } else {
      console.log("用户信息不存在,延时加载")
      setTimeout(function () {
        this.onShow();
      }.bind(that), 1000)
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    util.recordActionTime(this.data.startDate, 22, this.data.CurrentPid)
    this.setData({
      shouwTimer: false
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // 页面相关事件处理函数--监听用户下拉动作
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  //分享
  onShareAppMessage: function () {
    return {
      title: this.data.goodsDetail.ProductInfo.Name,
      path: this.data.pathGoods,
      success: function (res) {
        // 转发
        wx.showModal({
          title: '提示',
          content: '转发成功',
          showCancel: false
        })
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  //分享朋友圈
  onShareTimeline: function () {
    let that = this;
    let imageUrl = that.data.goodsDetail.ProductInfo.ShowImg;
    let query = that.data.query;
    return {
      title: that.data.goodsDetail.ProductInfo.Name,
      query: query,
      imageUrl: imageUrl
    }
  },
  //分销
  GetSharePagePath: function () {
    var that = this;
    var disId = wx.getStorageSync('disid')
    var agentId = wx.getStorageSync('agentid')
    console.log({
      userId: app.globalData.userInfo.Uid,
      storeId: app.globalData.storeId,
      agentId: agentId,
      disId: disId,
    });
    if (!disId) {
      disId = 0
    }
    if (!agentId) {
      agentId = 0
    }
    wx.request({
      url: app.globalData.host + '/api/Distributor/GetDistributorAndCreate',
      data: {
        userId: app.globalData.userInfo.Uid,
        storeId: app.globalData.storeId,
        agentId: agentId,
        disId: disId,
      },
      success: function (res) {
        console.log(res);
        if (res.data.Code == 0) {
          var path = '';
          let query = '';
          let pathGoods = '';
          let disId = 0;
          let agentId = 0;
          if (res.data.Data.IsAgent == 0) {
            disId = res.data.Data.Id;
            agentId = res.data.Data.AgentDId;
          } else {
            agentId = res.data.Data.Id;
          }
          pathGoods = "/pages/pintuan-details/index?disId=" + disId + "&agentId=" + agentId + "&id=" + that.data.CurrentPid;
          path = "/pages/pintuan-details/index?p=" + disId + "#" + agentId + "#" + that.data.CurrentPid;
          query = "disId=" + disId + "&agentId=" + agentId + "&id=" + that.data.CurrentPid + '&isFriendState=1';
          if (!that.data.productCode) {
            that.getWxaCode(path)
          }
          that.data.pathGoods = pathGoods;
          that.data.query = query;
        }
      }
    })
  },

  /**
  * 生成产品海报
  */

  //下载产品图片
  getAvaterInfo: function () {
    wx.showLoading({ title: '生成中...', mask: true, });
    var that = this;
    that.setData({ showpost: true })
    var goodsDetail = that.data.goodsDetail;
    console.log(that.data.goodsDetail)
    var productImage = goodsDetail.ProductImageList[0].ShowImg;
    if (productImage) {
      wx.downloadFile({
        url: productImage,
        success: function (res) {
          wx.hideLoading();
          if (res.statusCode === 200) {
            var productSrc = res.tempFilePath;
            that.getQrCode(productSrc);
          } else {
            wx.showToast({
              title: '产品图片下载失败！',
              icon: 'none',
              duration: 2000,
              success: function () {
                var productSrc = "";
                that.getQrCode(productSrc);
              }
            })
          }
        }
      })
    } else {
      wx.hideLoading();
      var productSrc = "";
      that.getQrCode(productSrc);
    }
  },

  //下载二维码
  getQrCode: function (productSrc) {
    wx.showLoading({ title: '生成中...', mask: true, });
    var that = this;
    var productCode = that.data.productCode;
    if (productCode) {
      wx.downloadFile({
        url: productCode,
        success: function (res) {
          wx.hideLoading();
          if (res.statusCode === 200) {
            var codeSrc = res.tempFilePath;
            that.sharePosteCanvas(productSrc, codeSrc);
          } else {
            wx.showToast({
              title: '二维码下载失败！',
              icon: 'none',
              duration: 2000,
              success: function () {
                var codeSrc = "";
                that.sharePosteCanvas(productSrc, codeSrc);
              }
            })
          }
        }
      })
    } else {
      wx.hideLoading();
      var codeSrc = "";
      that.sharePosteCanvas(productSrc, codeSrc);
    }
  },

  //canvas绘制分享海报
  sharePosteCanvas: function (avaterSrc, codeSrc) {
    wx.showLoading({
      title: '生成中...',
      mask: true,
    })
    var that = this;
    var productInfo = that.data.goodsDetail.ProductInfo;
    const ctx = wx.createCanvasContext('myCanvas');
    var width = "";
    wx.createSelectorQuery().select('#canvas-container').boundingClientRect(function (rect) {
      var height = rect.height;
      var right = rect.right;
      width = rect.width;
      var left = rect.left;
      ctx.setFillStyle('#fff');
      ctx.fillRect(0, 0, rect.width, height);

      //头像
      if (avaterSrc) {
        ctx.drawImage(avaterSrc, 0, 0, width, width);
        ctx.setFontSize(14);
        ctx.setFillStyle('#fff');
        ctx.setTextAlign('left');
      }


      //产品名称
      if (productInfo.Name) {
        const CONTENT_ROW_LENGTH = 16; // 正文 单行显示字符长度
        let [contentLeng, contentArray, contentRows] = that.textByteLength((productInfo.Name).substr(0, 18), CONTENT_ROW_LENGTH);
        ctx.setTextAlign('left');
        ctx.setFillStyle('#000');
        ctx.setFontSize(16);
        let contentHh = 22 * 1;
        for (let m = 0; m < contentArray.length; m++) {
          ctx.fillText(contentArray[m], 15, width + 35 + contentHh * m);
        }
      }


      //产品金额
      if (productInfo.ShopPrice || productInfo.ShopPrice == 0) {
        ctx.setFontSize(25);
        ctx.setFillStyle('#F57509');
        ctx.setTextAlign('left');
        ctx.fillText("¥" + productInfo.ShopPrice, left, width + 100); //电话
      }


      //  绘制二维码cardInfo.CardInfo.QrCode
      if (codeSrc) {
        ctx.drawImage(codeSrc, left + 185, width + 15, width / 4, width / 4)
        ctx.setFontSize(10);
        ctx.setFillStyle('#000');
        ctx.setTextAlign('right');
        ctx.fillText("微信扫码或长按识别", left + 266, width + 110);
      }

    }).exec()

    setTimeout(function () {
      ctx.draw();
      wx.hideLoading();
    }, 1000)

  },

  textByteLength(text, num) { // text为传入的文本  num为单行显示的字节长度
    let strLength = 0; // text byte length
    let rows = 1;
    let str = 0;
    let arr = [];
    for (let j = 0; j < text.length; j++) {
      if (text.charCodeAt(j) > 255) {
        strLength += 2;
        if (strLength > rows * num) {
          strLength++;
          arr.push(text.slice(str, j));
          str = j;
          rows++;
        }
      } else {
        strLength++;
        if (strLength > rows * num) {
          arr.push(text.slice(str, j));
          str = j;
          rows++;
        }
      }
    }
    arr.push(text.slice(str, text.length));
    return [strLength, arr, rows] //  [处理文字的总字节长度，每行显示内容的数组，行数]
  },

  //点击保存到相册
  saveShareImg: function () {
    var that = this;
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas',
        success: function (res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success(res) {
              wx.showModal({
                content: '图片已保存到相册，赶紧晒一下吧~',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success: function (res) {
                  that.closePoste();
                  if (res.confirm) { }
                },
                fail: function (res) { }
              })
            },
            fail: function (res) {
              wx.showToast({
                title: res.errMsg,
                icon: 'none',
                duration: 2000
              })
            }
          })
        }
      });
    }, 1000);
  },
  closePoste: function () {
    this.setData({ showpost: false })
  },
  //跳聊天页
  // tapChat: function () {
  //   if (app.globalData.userStaff) {
  //     var name = encodeURIComponent(app.globalData.userStaff.Name);
  //     var seltoid = app.globalData.userStaff.Uid
  //     wx.navigateTo({
  //       url: '/pages/weijieke/Business/Business?seltoid=' + seltoid + '&name=' + name,
  //     })
  //   }
  // },
  //获取新消息提示
  login: function (cb) {
    var that = this;
    tls.login({
      success: function (data) {
        that.setData({
          Identifier: data.Identifier,
          UserSig: data.UserSig
        })
        cb();
      }
    });
  },
  initIM: function (cb) {
    var that = this;
    var onSendMsgCallback = function (dataMsg) {
      that.setData({
        showTopPopup: true,
        FromAccountNick: dataMsg.FromAccountNick,
        FromAccountImage: dataMsg.FromAccountImage,
        FromAccount: dataMsg.FromAccount
      }) //新消息提示
      setTimeout(function () {
        that.setData({
          showTopPopup: false
        })
      }, 5000)
    }
    var getHistoryMsgCallback = function () { }
    webimhandler.init({
      accountMode: Config.accountMode,
      accountType: Config.accountType,
      sdkAppID: Config.sdkappid,
      selType: webim.SESSION_TYPE.C2C,
      selToID: app.globalData.userStaff.Uid,
      selSess: null, //当前聊天会话
      getHistoryMsgCallback: getHistoryMsgCallback, //获取历史消息回调
      onSendMsgCallback: onSendMsgCallback //发送消息回调
    });

    //当前用户身份
    var loginInfo = {
      'sdkAppID': Config.sdkappid, //用户所属应用id,必填
      'appIDAt3rd': Config.sdkappid, //用户所属应用id，必填
      'accountType': Config.accountType, //用户所属应用帐号类型，必填
      'identifier': that.data.Identifier, //当前用户ID,必须是否字符串类型，选填
      'identifierNick': app.globalData.userInfo.NickName, //当前用户昵称，选填
      'userSig': that.data.UserSig, //当前用户身份凭证，必须是字符串类型，选填
      'headurl': app.globalData.userInfo.Avatar //当前用户头像
    };

    //监听连接状态回调变化事件
    var onConnNotify = function (resp) {
      switch (resp.ErrorCode) {
        case webim.CONNECTION_STATUS.ON:
          webim.Log.warn('连接状态正常...');
          break;
        case webim.CONNECTION_STATUS.OFF:
          webim.Log.warn('连接已断开，无法收到新消息，请检查下你的网络是否正常');
          break;
        default:
          webim.Log.error('未知连接状态,status=' + resp.ErrorCode);
          break;
      }
    };


    //监听事件
    var listeners = {
      "onConnNotify": webimhandler.onConnNotify, //选填
      "onMsgNotify": webimhandler.onMsgNotify, //监听新消息(私聊(包括普通消息和全员推送消息)，普通群(非直播聊天室)消息)事件，必填
    };

    //其他对象，选填
    var options = {
      'isAccessFormalEnv': true, //是否访问正式环境，默认访问正式，选填
      'isLogOn': false //是否开启控制台打印日志,默认开启，选填
    };


    //独立模式sdk登录
    webimhandler.sdkLogin(loginInfo, listeners, options);
  },
  toggleTopPopup() {
    this.setData({
      showTopPopup: !this.data.showTopPopup
    });
  },
  tapChatFrom: function () {
    if (app.globalData.userStaff) {
      // var name = encodeURIComponent(this.data.FromAccountNick);
      // var seltoid = this.data.FromAccount;
      // wx.navigateTo({
      //   url: '/pages/weijieke/Business/Business?seltoid=' + seltoid + '&name=' + name,
      // })
      util.tapChat(app.globalData.userStaff);
    }
  },
  // 底部弹出层
  showModal: function () {
    // 显示遮罩层
    this.onProductSKU(this.data.CurrentPid)
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },
  //接口取值
  onProductSKU: function (pid) {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/Store/Product',
      data: {
        pid: pid
      },
      success: function (res) {
        console.log(res)
        if (res.data.Code == 0) {
          var skuList = res.data.Data.ProductSKUList
          var skuTitle = res.data.Data.CurrProductSkuList
          for (var k = 0; k < skuTitle.length; k++) {//初始化二维数组
            skuTitle[k].arr = []
            skuTitle[k].nameArr = []
          }
          that.ProductSKU(skuTitle, skuList);
        } else {
          wx.showModal({
            title: '获取失败',
            content: '',
            showCancel: false
          })
        }
      }
    })
  },
  //重新push新数组
  ProductSKU: function (skuTitle, skuList) {
    var that = this;
    var skuTitles = skuTitle
    var skuList = skuList
    for (var i = 0; i < skuTitles.length; i++) {
      for (var j = 0; j < skuList.length; j++) {
        if (skuTitles[i].AttrId == skuList[j].AttrId) {
          var f = {}
          f.AttrId = skuList[j].AttrId
          f.AttrName = skuList[j].AttrName
          f.AttrValue = skuList[j].AttrValue
          f.Pid = skuList[j].Pid
          f.RecordId = skuList[j].RecordId
          f.IsInput = skuList[j].IsInput
          f.InputValue = skuList[j].InputValue
          f.sid = 0
          f.ShowImg = app.globalData.image800_800host + skuList[j].ShowImg
          skuTitles[i].arr.push(f)
          if (skuList[j].IsInput == 1) {//手动输入
            var skuValue = skuList[j].InputValue
          } else {
            var skuValue = skuList[j].AttrValue
          }
          if (!that.check(skuTitles[i].nameArr, skuValue)) {
            skuTitles[i].nameArr.push({
              attrvalue: skuList[j].AttrValue, kid: 0, AttrId: skuList[j].AttrId, IsInput: skuList[j].IsInput, InputValue: skuList[j].InputValue
            })
          }
        }
      }
    }
    that.setData({
      skuTitles: skuTitles
    })
  },
  //数组去重
  check: function (arr, text) {
    var state = false;  //默认不存在
    if (arr.length > 0) {
      for (var i = 0; i < arr.length; i++) {
        if (text == arr[i].attrvalue || text == arr[i].InputValue) {
          state = true; //已经存在
          break;
        }
      }
    }
    return state;
  },
  //规格选择颜色变化
  selectAttr: function (e) {
    var that = this;
    var namearr = e.currentTarget.dataset.namearr
    var attrid = e.currentTarget.dataset.attrid
    var skulist = that.data.skuTitles
    var kid = 0//颜色变化初始值
    for (var i = 0; i < skulist.length; i++) {//一级数组
      var nameArr = skulist[i].nameArr
      for (var j = 0; j < nameArr.length; j++) {//二级数组
        if (nameArr[j].IsInput == 1) {
          var nameAttrValue = nameArr[j].InputValue
        } else {
          var nameAttrValue = nameArr[j].attrvalue
        }
        if (nameAttrValue == namearr) {
          if (nameArr[j].kid == 0) {
            nameArr[j].kid = 1
          }
          else {
            nameArr[j].kid = 0
          }
        }
        else if (nameAttrValue != namearr && attrid == nameArr[j].AttrId) {
          nameArr[j].kid = 0
        }
        else if (attrid != nameArr[j].AttrId) {
          if (nameArr[j].kid != 1) {
            nameArr[j].kid = 3
            that.selectionPid(skulist, namearr, attrid)
          }
        }
      }
    }
    that.setData({
      skuTitles: skulist
    })
    var pidArr = []
    for (var p = 0; p < skulist.length; p++) {//选中对应kid筛选pid
      var nameArry = skulist[p].nameArr
      var arry = skulist[p].arr
      for (var h = 0; h < nameArry.length; h++) {
        if (nameArry[h].kid == 1) {
          if (nameArry[h].IsInput == 0) {
            var nameAttrValue = nameArry[h].attrvalue
          } else {
            var nameAttrValue = nameArry[h].InputValue
          }
          for (var m = 0; m < arry.length; m++) {
            if (arry[m].IsInput == 0) {
              var arrAttrValue = arry[m].AttrValue
            } else {
              var arrAttrValue = arry[m].InputValue
            }
            if (nameAttrValue == arrAttrValue) {
              pidArr.push(arry[m].Pid)
            }
          }
        }
      }
    }
    var nary = pidArr.sort();
    that.arrRepeat(nary, skulist.length)//一共几组sku skulist.length
  },
  //查找数组重复次数的组合pid
  arrRepeat: function (arr, skuCount) {
    var that = this;
    let pid = 0;
    var arrStr = JSON.stringify(arr), str;
    for (var i = 0; i < arr.length; i++) {
      if ((arrStr.match(new RegExp(arr[i], "g")).length) == skuCount) {//出现重复的次数等于sku组的出现次数
        that.setData({
          CurrentPid: arr[i]//最终的组合pid
        })
        pid = arr[i]
      }
    }
    if (pid != 0) {
      that.getGoodsInfo()
    }
  },
  //返回选中的pid
  selectionPid: function (skulist, text, attrid) {
    var that = this;
    for (var i = 0; i < skulist.length; i++) {
      if (attrid == skulist[i].AttrId) {
        var arr = skulist[i].arr
        for (var j = 0; j < arr.length; j++) {
          if (arr[j].IsInput == 0) {
            var arrAttrValue = arr[j].AttrValue
          } else {
            var arrAttrValue = arr[j].InputValue
          }
          if (text == arrAttrValue) {
            var Pid = arr[j].Pid
            that.otherPid(skulist, Pid, attrid)
          }
        }
      }
    }
  },
  //判断另一组可选择的规格值
  otherPid: function (skulist, pid, attrid) {
    var that = this;
    var valueArr = []
    for (var i = 0; i < skulist.length; i++) {
      if (attrid != skulist[i].AttrId) {
        var arr = skulist[i].arr
        var nameArr = skulist[i].nameArr
        for (var j = 0; j < arr.length; j++) {
          if (pid == arr[j].Pid) {
            if (arr[j].IsInput == 0) {
              var AttrValue = arr[j].AttrValue
            } else {
              var AttrValue = arr[j].InputValue
            }
            that.check2(valueArr, AttrValue)
            if (!that.check2(valueArr, AttrValue)) {
              valueArr.push(AttrValue)
              for (var f = 0; f < valueArr.length; f++) {
                for (var k = 0; k < nameArr.length; k++) {
                  if (nameArr[k].IsInput == 0) {
                    var nameArrValue = nameArr[k].attrvalue
                  } else {
                    var nameArrValue = nameArr[k].InputValue
                  }
                  if (valueArr[f] == nameArrValue && nameArr[k].kid != 1) {
                    nameArr[k].kid = 0
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  //数组去重
  check2: function (arr, text) {
    var state = false;  //默认不存在
    if (arr.length > 0) {
      for (var i = 0; i < arr.length; i++) {
        if (text == arr[i]) {
          state = true; //已经存在
          break;
        }
      }
    }
    return state;
  },
  //跳聊天页
  tapChat: function () {
    let ProductInfo = this.data.goodsDetail.ProductInfo;
    if (app.globalData.userStaff) {
      // var name = encodeURIComponent(app.globalData.userStaff.Name);
      // var seltoid = app.globalData.userStaff.Uid
      // wx.navigateTo({
      //   url: '/pages/weijieke/Business/Business?seltoid=' + seltoid + '&name=' + name + '&productname=' + encodeURIComponent(ProductInfo.Name) + '&shopprice=' + ProductInfo.ShopPrice + '&showimg=' + ProductInfo.ShowImg,
      // })
      util.tapChat(app.globalData.userStaff);
    }
  },
})